// $Id$
package de.servicezombie.cxf;

import org.apache.cxf.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JaxrsServletApiFactory {

	private static final Logger log = LoggerFactory.getLogger(JaxrsServletApiFactory.class);

	private static Class<? extends JaxrsServletApiAdapterProvider> provider = ServletApiAdapterCxf24Provider.class;

	/**
	 * replace provider for unit tests
	 */
	public static void setProvider(Class<? extends JaxrsServletApiAdapterProvider> provider) {
		JaxrsServletApiFactory.provider = provider;
	}

	public ServletApiAdapter build(Message message) {

		if (log.isDebugEnabled()) {
			log.debug("build: >> " + message);
		}

		JaxrsServletApiAdapterProvider providerInstance;
		try {
			providerInstance = provider.newInstance();
		}
		catch (InstantiationException e) {
			throw new IllegalStateException("unable to build instance of " + provider + ": " + e.getMessage());
		}
		catch (IllegalAccessException e) {
			throw new IllegalStateException("unable to build instance of " + provider + ": " + e.getMessage());
		}

		providerInstance.setMessage(message);
		ServletApiAdapter instance = providerInstance.getServletApiAdapter();

		if (log.isDebugEnabled()) {
			log.debug("build: << " + instance);
		}
		return instance;
	}

	static void logIfNotNull(Object data, String message) {
		if (data == null && log.isInfoEnabled()) {
			log.info(message);
		}
	}

}
